package com.cbgolf.oa.net;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.alibaba.fastjson.JSONObject;
import com.cbgolf.oa.activity.publiz.LoadingActivity;
import com.cbgolf.oa.app.AppManager;
import com.cbgolf.oa.entity.NetResponse;
import com.cbgolf.oa.inteface.INetCallBack;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.ErrorUtil;
import com.cbgolf.oa.util.Util;
import com.tencent.bugly.crashreport.CrashReport;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @author Created by lq on 2016/11/23.
 */

public class NetCallBack implements Callback {

  private Handler handler = new Handler(Looper.getMainLooper());
  private INetCallBack listener;
  private String message;
  private int statusCode = 0;
  private String data;
  private String result;

  private final String TOKEN_KEY = "X-Auth-Token";
  private final String TOKEN = "token";
  private final String STATUS = "status";
  private final String DATA = "data";
  private final String MESSAGE = "message";
  private final String RESULT = "result";

  public NetCallBack(INetCallBack listener) {
    this.listener = listener;

  }

  @Override
  public void onFailure(final Call call, final IOException e) {
    if (!NetUtils.isTest()) {
      CrashReport.postCatchedException(new Throwable("requestUrl:" + call.request().url()
          + "---error:" + e.toString()));
    }
    Log.e("errorUrl:", call.request().url() + "");
    final NetResponse response = new NetResponse();
    response.statusCode = 300;
    response.errorMsg = ErrorUtil.NETERROR;
    handler.post(() -> listener.onResponse(response));
  }

  @Override
  public void onResponse(final Call call, final Response response) {
    try {
      result = response.body().string();
    } catch (IOException e) {
      e.printStackTrace();
    }
    final String token = response.header(TOKEN_KEY);
    statusCode = (response.code() >= 200 && response.code() < 300) ? 200 : response.code();
    JSONObject json = DataUtil.getJson(result);
    if (DataUtil.isContainsJsonkey(json, STATUS, DATA)) {
      statusCode = DataUtil.getJsonInt(json, STATUS, 0);
      data = DataUtil.getJsonString(json, DATA);
      if (NetUtils.SUCCESS != statusCode) {
        message = DataUtil.getJsonString(json, MESSAGE);
        Class clazz = AppManager.getNewInstance().currentActivity().getClass();
        if (NetUtils.TOKEN_LOSE == statusCode
            && null != clazz && !clazz.equals(LoadingActivity.class)) {
          message = "登录信息过期";
          Util.showTokenBad();
        }
      }
    } else {
      data = result;
      if (!response.isSuccessful() && !Util.isNull(result)) {
        JSONObject oldJson = DataUtil.getJson(result);
        message = DataUtil.getJsonString(oldJson, MESSAGE);
        int status = DataUtil.getJsonInt(oldJson, STATUS, 0);
        if (NetUtils.TOKEN_LOSE == status && message.contains(TOKEN)) {
          Util.showTokenBad();
          message = "登录信息过期";
        }
      }
    }
    if (NetUtils.SUCCESS != statusCode && !NetUtils.isTest()) {
      CrashReport.postCatchedException(new Throwable("requestUrl:" + call.request().url()
          + "---Token:" + DataUtil.getToken()
          + "---Result:" + result));
    }
    if (NetUtils.SUCCESS != statusCode) {
      Log.e("errorUrl:", call.request().url() + "");
    }

    handler.post(() -> {
      NetResponse res = new NetResponse();
      res.statusCode = statusCode;
      res.result = Util.isNull(data) ? (Util.isNull(result) ? RESULT : result) : data;
      res.token = token;
      res.errorMsg = (Util.isNull(message) && statusCode != 200) ? ErrorUtil.NETERROR : message;
//      if (NetUtils.isTest()) {
      Log.e("result:", result + "-------");
      Log.e("data:", data + "-----------");
      Log.e("code:", statusCode + "---------");
      Log.e("msg:", res.errorMsg + "-----");
//      }
      listener.onResponse(res);
    });
  }
}
